﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
using Road3App.Model.CrossroadNs;

namespace Road3App.Services.Converters
{
    class CrossRoadVehicleRotationConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            double result = 0.0;

            Cell prev, current, next;
            prev = current = next = null;

            if(values[0] != DependencyProperty.UnsetValue)
                prev = (Cell)values[0];
            if(values[0] != DependencyProperty.UnsetValue)
                current = (Cell)values[1];
            if(values[0] != DependencyProperty.UnsetValue)
                next = (Cell)values[2];

            result = GetRotationAngle(prev, current, next);
            return result;
        }

        public static int GetRotationAngle(Cell prev, Cell next)
        {
            if (next.Coords.X == prev.Coords.X)
            {
                if (next.Coords.Y > prev.Coords.Y)
                    return 180;
                if (next.Coords.Y < prev.Coords.Y)
                    return 0;
            }
            if (next.Coords.Y == prev.Coords.Y)
            {
                if (next.Coords.X > prev.Coords.X)
                    return 90;
                if (next.Coords.X < prev.Coords.X)
                    return 270;
            }
            return -1;
        }

        public static int GetRotationAngle(Cell prev, Cell current, Cell next)
        {
            if (next == null && prev == null)
                return -1;
            else if (next != null && prev != null)
            {
                int angle = GetRotationAngle(prev, next);
                if (angle != -1)
                    return angle;

                if (next.Coords.X > prev.Coords.X)
                {
                    if (next.Coords.Y > prev.Coords.Y)
                        return 135;
                    if (next.Coords.Y < prev.Coords.Y)
                        return 45;
                }
                if (next.Coords.X < prev.Coords.X)
                {
                    if (next.Coords.Y > prev.Coords.Y)
                        return 225;
                    if (next.Coords.Y < prev.Coords.Y)
                        return 315;
                }
            }
            if (prev == null)
                return GetRotationAngle(current, next);
            if (next == null)
                return GetRotationAngle(prev, current);
            return -1;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
